import { Node, UITransform } from 'cc';
import { ecs } from 'db://app-game/libs/ecs/ECS';
import { ECSEntity } from 'db://app-game/libs/ecs/ECSEntity';
import { Circle } from 'db://app-game/libs/math/auad-tree/Circle';
import { Rectangle } from 'db://app-game/libs/math/auad-tree/Rectangle';
import { smc } from '../../../singleton/SingletonModuleComp';

/** 特效碰撞组件 */
@ecs.register('EffectsCollision')
export class EffectsCollisionComp extends ecs.Comp {
  /** 特效节点 */
  node: Node = null!;
  /** 特效碰撞体类型 */
  colliderType: 'Circle' | 'Rectangle' = 'Circle';

  /** 碰撞回调 */
  onCollision: Function | null = null;

  reset(entity: ecs.Entity): void {
    this.node = null!;
    this.colliderType = 'Circle';
    this.onCollision = null;
  }
}

/** 特效碰撞系统 */
@ecs.register('EffectsCollision')
export class EffectsCollisionSystem
  extends ecs.ComblockSystem<ecs.Entity>
  implements ecs.ISystemUpdate
{
  filter(): ecs.IMatcher {
    return ecs.allOf(EffectsCollisionComp);
  }
  update(entity: ECSEntity, dt: number): void {
    const ecc = entity.get(EffectsCollisionComp);

    let collider: Circle<{ node: Node }> | Rectangle<{ node: Node }>;
    const effectsUI = ecc.node.getComponent(UITransform);
    if (ecc.colliderType === 'Circle') {
      collider = new Circle({
        xr: effectsUI.width / 2,
        yr: effectsUI.height / 2,
        x: effectsUI.node.position.x,
        y: effectsUI.node.position.y,
      });
    } else {
      collider = new Rectangle({
        x: effectsUI.node.position.x,
        y: effectsUI.node.position.y,
        width: effectsUI.width,
        height: effectsUI.height,
      });
    }

    // 4.检查有可能碰撞的节点
    const colliderList = smc.level.LevelMap.colliderList({
      name: '',
      circle: collider,
    });

    if (colliderList.length > 0) {
      ecc.onCollision?.call(colliderList);
    }
  }
}
